package com.loby.data.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.collections.map.ListOrderedMap;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @Author: GaoAng
 * @Description: Json工具类
 * @Date: 2021/4/17 16:29
 * @Version: 1.0
 */
public class JsonTools {

    /**
     * json转换list.
     */
    public static List<Map<String, Object>> parseJSON2List(String jsonStr){
        JSONArray jsonArr = JSONArray.fromObject(jsonStr);
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        Iterator<JSONObject> it = jsonArr.iterator();
        while(it.hasNext()){
            JSONObject json2 = it.next();
            list.add(parseJSON2Map(json2.toString()));
        }
        return list;
    }

    /**
     * json转换map.
     */
    public static Map<String, Object> parseJSON2Map(String jsonStr){
        ListOrderedMap map = new ListOrderedMap();
        //最外层解析
        JSONObject json = JSONObject.fromObject(jsonStr);
        System.out.println(json);
        for(Object k : json.keySet()){
            Object v = json.get(k);
            //如果内层还是数组的话，继续解析
            if(v instanceof JSONArray){
                List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
                Iterator<JSONObject> it = ((JSONArray)v).iterator();
                while(it.hasNext()){
                    JSONObject json2 = it.next();
                    list.add(parseJSON2Map(json2.toString()));
                }
                map.put(k.toString(), list);
            } else {
                map.put(k.toString(), v);
            }
        }
        return map;
    }

    /**
     * 通过HTTP获取JSON数据.
     */
    public static List<Map<String, Object>> getListByUrl(String url){
        try {
            //通过HTTP获取JSON数据
            InputStream in = new URL(url).openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line;
            while((line=reader.readLine())!=null){
                sb.append(line);
            }
            return parseJSON2List(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过HTTP获取JSON数据.
     */
    public static Map<String, Object> getMapByUrl(String url){
        try {
            //通过HTTP获取JSON数据
            InputStream in = new URL(url).openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder sb = new StringBuilder();
            String line;
            while((line=reader.readLine())!=null){
                sb.append(line);
            }
            return parseJSON2Map(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * map转换json.
     */
    public static String mapToJson(Map<String, String> map) {
        Set<String> keys = map.keySet();
        String key = "";
        String value = "";
        StringBuffer jsonBuffer = new StringBuffer();
        jsonBuffer.append("{");
        for (Iterator<String> it = keys.iterator(); it.hasNext();) {
            key = (String) it.next();
            value = map.get(key);
            jsonBuffer.append(key + ":" +"\""+ value+"\"");
            if (it.hasNext()) {
                jsonBuffer.append(",");
            }
        }
        jsonBuffer.append("}");
        return jsonBuffer.toString();
    }


    //test
    public static void test(String[] args) {
        String a = "{\n" +
                "\t\"merapp\":\"X001\",\n" +
                "\t\"version\":\"1\",\n" +
                "\t\"device\":\"1\",\n" +
                "\t\"tranName\":\"notifyOrderPost\",\n" +
                "\t\"charset\":\"UTF-8\",\n" +
                "\t\"reqData\":\"eyJhbW91bnQiOiIxMDAuMDAiLCJjb21tcGFyYSI6IiIsIm9yZERhdGUiOiIyMDIxMDEwNyIsIm9yZE5vIjoiQlNUSkVEVVBIRDZFQzUxNjEwMDE2ODY1MTM0IiwicGxhdGZvcm1ObyI6IjIwMjEwMTA3MjU2OTU0Njk3NTgyNjQyMTc3IiwidHJhbkJhbmtObyI6IjIwMjEwMTA3MjIwMDE0NzExMTA1MTIwMzcxMTgiLCJ0cmFuRGF0ZSI6IjIwMjEwMTA3IiwidHJhblN0YXR1cyI6IjEiLCJ0cmFuVGltZSI6IjE5MDgwNCJ9\",\n" +
                "\t\"sign\":\"cS9DR2tBbTRLY0g4Z0N2RDJHNkVMaFhZZ1dYYXRaMjhyVTAydVppZVA2eklKT2piUDA5YllwR3Y1ZFBUWElhVGUrYmhtQ3VTZSsrV3YzZzdQclcxN2RnVUJPbG9PN0NocXIrQi9sNTJzTFdjUWZmRUZyMVNKaEJSRURIdE90UlZFWDRIY3pLYlJqeEVuVWdMMVlPSUJ2TDdTTi9QUmtMcXBXTlpUTmF2dzF3PQ==\"\n" +
                "}";
        Map<String, Object> stringObjectMap = parseJSON2Map(a);
        System.out.println(stringObjectMap.toString());
    }

}
